<template>
    <el-card>
    <!-- form 查询表单 -->
    <el-form :model="order" ref="formRef" label-width="auto" label-position="right" style="padding-bottom: 10px;">
        <el-row :gutter="20">
            <el-col :span="5">
                <el-form-item label="订单编号" prop="dingdan_num">
                    <el-input v-model="order.dingdan_num" placeholder="请输入订单编号" clearable/>
                </el-form-item>
            </el-col>
            <el-col :span="5">
                <el-form-item label="用户号码" prop="phone">
                    <el-input v-model="order.phone" placeholder="请输入用户号码" clearable/>
                </el-form-item>
            </el-col>
            <el-col :span="5">
                <el-form-item label="状态" prop="state">
                    <el-select v-model="order.state" placeholder="请选择状态">
                        <el-option label="全部" value="7"></el-option>
                        <el-option label="已拒绝" value="1"></el-option>
                        <el-option label="已完成订单" value="5"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="4">
                <el-button type="primary" @click="doList">查询</el-button>
                <el-button type="default" @click="resetForm(formRef)">重置</el-button>
            </el-col>
        </el-row>
    </el-form>

    <!-- table 表格 -->
    <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="80" sortable/>
        <el-table-column prop="dingdan_num" label="订单编号" sortable/>
        <el-table-column prop="phone" label="用户号码"/>
        <el-table-column prop="time" label="起送时间" sortable/>
        <el-table-column prop="end_time" label="完成时间" sortable/>
        <el-table-column prop="state" label="状态" sortable>

                <template #default="scope">
                <el-tag v-if="scope.row.state === '0'" type="warning">进行中</el-tag>
                <el-tag v-else-if="scope.row.state === '1'" type="danger">已拒绝</el-tag>
                <el-tag v-else-if="scope.row.state === '5'" type="success">已完成订单</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="price" label="金额"/>
        <el-table-column label="操作" width="300">
            <template #default="scope">
                <el-button type="primary" @click="showDetailPage(scope.row)+showDetailPage2(scope.row.dingdan_num)">详情</el-button>

            </template>
        </el-table-column>
    </el-table>
    < <!-- 分页控件 -->
    <div class="pagination">
        <el-pagination
            style="float: left;"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[5, 10, 20, 50]"
            v-model:current-page="page.pageNum"
            v-model:page-size="page.pageSize"
            :total="page.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
    </el-card>
    <!-- 详情 页面 -->
    <detail-page ref="detailPageRef"></detail-page>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="订单详情" width="50%">

        <el-table :data="currentOrderItems" style="margin-top: 20px;">
            <el-table-column prop="dish_name" label="菜品名称"/>
            <el-table-column prop="num" label="数量"/>
            <el-table-column prop="price" label="金额"/>
        </el-table>

        <h3>订单编号：{{remark.dingdan_num}}</h3>
        <h3>用户id：{{remark.user_id}}</h3>
        <h3>接单骑手：{{remark.rider_id}}</h3>
        <h3>下单时间：{{remark.time}}</h3>
        <h3>完成时间：{{remark.end_time}}</h3>
        <h3>总金额：{{remark.money}}</h3>
        <h2>备注：{{ remark.remark }}</h2>
    </el-dialog>
</template>

<script setup lang="ts">
import {ref, onMounted} from 'vue'
import axios from 'axios'

import {ElMessage, FormInstance} from "element-plus";
import storage from "../../../storage.ts";
import {useRoute} from "vue-router";

const shopId = localStorage.getItem('shopInfo') ? JSON.parse(localStorage.getItem('shopInfo')).id : null;
const shop = ref({
    id: shopId,
    shopname: "",
    pwd: "",
    phone: "",
    address: "",
    picture: "",
    checked: "",
    state: "",
    income: "",
    score: ""
})

const remark = ref({
    user_id: '',
    remark: '',
    time: '',
    dingdan_num: '',
    phone: '',
    rider_id: '',
    money: '',
    end_time: '',
})

// form 查询表单绑定的数据对象：order
const order = ref({
    id: '',
    dingdan_num: '',
    user_id:'',
    state:'7',
    shop_id: shopId,
    time: "",
    phone: "",
})
// table 数据表格绑定的数据对象：tableData
const tableData = ref([])

// 查询
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);

// 分页相关变量
const page = ref({
    pageNum: 1,     // 当前页码
    pageSize: 5,   // 每页显示的记录数
    pages: 0,       // 总页数
    total: 0        // 总记录数
});
// 分页事件处理
const handleSizeChange = (val: number) => {
    page.value.pageSize = val;
    page.value.pageNum = 1;
    doList();
};

const handleCurrentChange = (val: number) => {
    page.value.pageNum = val;
    doList();
};

// 分页重置
const doPageReset = () => {
    page.value.pageNum = 1;
    page.value.pageSize = 5;
    page.value.pages = 0;
    page.value.total = 0;
}
const doList = async () => {
    try {
        const params = {
            ...order.value,
            pageNum: page.value.pageNum,
            pageSize: page.value.pageSize
        };

        const { data } = await axios.get('/api/dingdan', { params });
        console.log('API响应数据:', data);

        // 确保处理正确的分页数据结构
        if (data && data.list) {
            // 处理返回的分页数据
            tableData.value = data.list || [];

            // 从响应中获取分页信息，如果不存在则保持原有值
            page.value.total = data.total || page.value.total;
            page.value.pages = data.pages || page.value.pages;
        } else {
            // 如果数据结构不符合预期，给出提示并重置表格数据
            ElMessage.error('获取数据失败');
            tableData.value = [];
        }
    } catch (error) {
        console.error('请求失败:', error);
        ElMessage.error('请求失败，请检查网络连接');
        tableData.value = [];
    }


}

// 重置表单
const resetForm = (formEl: any) => {
    if (!formEl) return
    formEl.resetFields()
}
const route = useRoute();

const user = ref();
// 初始化
onMounted(async () => {
    doList()

    user.value = storage.getUser();
    storage.removeUser();

    try {
        // 优先从路由参数中获取店铺ID
        const shopId = route.query.id;
        if (shopId) {
            // 调用后端接口获取店铺信息
            const {data} = await axios.get(`/api/shop/${shopId}`);
            shop.value = data;
            console.log(shop.value);

        } else {
            // 如果没有路由参数，则尝试从localStorage中获取
            const storedShopInfo = localStorage.getItem('shopInfo');
            if (storedShopInfo) {
                shop.value = JSON.parse(storedShopInfo);

            }
        }
    } catch (error) {
        console.error('获取店铺信息失败:', error);
    }
})
const formRef = ref<FormInstance>();

// 查看详情
const detailPageRef = ref()
const showDetailPage = async (row) => {
    try {
        const {data} = await axios.get('/api/dingdandetail/'+row.dingdan_num)
        console.log(data);
        currentOrderItems.value = data; // 假设后端返回的订单详情包含菜品列表
        dialogVisible.value = true;
    } catch (error) {
        ElMessage.error('查找失败')
    }
}

const showDetailPage2 = async (row) => {
    try {
        const {data} = await axios.get('/api/dingdan/dingdan_num/'+row)
        ElMessage.success('查找成功');
        remark.value = data;
        dialogVisible.value = true;

    } catch (error) {
        ElMessage.error('查找失败')
    }
}


// 弹窗相关变量
const dialogVisible = ref(false);
const currentOrder = ref({});
const currentOrderItems = ref([]);
</script>